package com.org.manhu.chargehelper.broadcastreceiver;

import java.text.DecimalFormat;
import java.util.Map;

import com.org.manhu.chargehelper.ChargeApplication;
import com.org.manhu.chargehelper.constant.Constant;
import com.org.manhu.chargehelper.tools.ApkInfoUtils;
import com.org.manhu.chargehelper.tools.DeviceInfo;
import com.org.manhu.chargehelper.tools.FileUtil;
import com.org.manhu.chargehelper.tools.JsonUtil;
import com.org.manhu.chargehelper.tools.NetUtils;
import com.org.manhu.chargehelper.tools.Sever;
import com.org.manhu.chargehelper.tools.SharedPreferncesUtil;
import com.org.manhu.chargehelper.tools.StringUtils;
import com.org.manhu.chargehelper.tools.ToastUtils;
import com.org.manhu.chargehelper.webservice.AsyncProcessData;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

/**
 * @文件名：AppReceiver.java3
 * @包名：com.org.manhu.broadcast
 * @作者：李朋辉 @QQ：892839211
 * @创建时间：2015年1月12日 上午11:21:07
 *
 * @描述：应用安装成功的监听
 */
public class InstallSuccessReceiver extends BroadcastReceiver {

	private static final int PACKAGE_NAME_START_INDEX = 8;
	private DecimalFormat df = new DecimalFormat("0.00");
	private AsyncProcessData request;
	private Context context;
	private String appId;

	private String channelId;
	private String devId;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			String json = msg.getData().getString("jsonStr");
			if (Constant.USER_SETUP_RES.equals(msg.obj.toString())) {
				Map<String, String> feedbackMap = JsonUtil.parseAll(json);
				if (feedbackMap != null) {
					if (feedbackMap.get("Code").equals("0")) {
						clientInit();
					} else {
						Map<String, String> map = JsonUtil.parseAll(json);
						if (map != null) {
							if ("1".equals(map.get("Code"))) {
								request.getRequestData(
										mHandler,
										Constant.GET_USER_INFO,
										"AuthKey",
										ChargeApplication.getInitInfo().get(
												"AuthKey"));
							}
						}
					}
				} else {
					userSetupRes(context, appId);
				}
			} else if (Constant.GET_USER_INFO.equals(msg.obj.toString())) {
				Map<String, String> map = JsonUtil.parseAll(json);
				if (map != null) {
					float money = Float.parseFloat(map.get("Money"));
					Intent intent = new Intent();
					intent.setAction(Constant.ACTION_UPDATE_MONEY);
					intent.putExtra("money", money);
					ChargeApplication.mApplicationContext.sendBroadcast(intent);
					SharedPreferncesUtil.saveMoney(
							ChargeApplication.mApplicationContext,
							Float.parseFloat(df.format(money)));
				}
			} else if (Constant.CLIENT_INIT.equals(msg.obj.toString())) {
				Map<String, String> initMap = JsonUtil.parseAll(json);
				if (initMap != null) {
					ChargeApplication.updateInitInfo(initMap);
					userSetupRes(context, appId);
				} else {
					clientInit();
				}
			}
		};
	};

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		this.context = context;
		if (intent == null) {
			return;
		}

		if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
			String data = intent.getDataString();

			if (data == null || data.length() <= PACKAGE_NAME_START_INDEX) {
				return;
			}

			String packageName = data.substring(PACKAGE_NAME_START_INDEX);

			String appName = ApkInfoUtils.getAppNameByPackageName(context,
					packageName);
			if (ChargeApplication.offlineInstallList.size() > 0) {
				String appId = ChargeApplication.offlineInstallList
						.get(packageName);
				Sever.getInstance().sendMessageToClient(
						StringUtils.installSuccess(appId));
				ToastUtils.showShort(context, appName + "安装成功");
				ChargeApplication.offlineInstallList.remove(packageName);
			} else if (ChargeApplication.installList.size() > 0) {
				request = new AsyncProcessData();
				appId = ChargeApplication.installList.get(packageName);

				if (!TextUtils.isEmpty(appId) && appId != null) {
					userSetupRes(context, appId);
				}
			}
		}
	}

	/**
	 * @描述： 客户端初始化，获取AuthKey
	 */
	private void clientInit() {
		if (NetUtils.isConnected(context)) {
			if (Constant.IS_USE_BOXINFO) {
				channelId = SharedPreferncesUtil.getBoxInfo(context,
						Constant.SP_BOX_CHANNELID);
				devId = SharedPreferncesUtil.getBoxInfo(context,
						Constant.SP_BOX_DEVID);
			} else {
				channelId = "0";
				devId = "0";
			}
			request.getRequestData(mHandler, Constant.CLIENT_INIT, "AuthKey",
					"", "Imei", DeviceInfo.getIMEI(), "Imsi",
					DeviceInfo.getIMSI(), "AndroidId",
					DeviceInfo.getAndroidID(), "PhoneTypeId",
					DeviceInfo.getDeviceModel(), "ChannelId", channelId,
					"DevId", devId);
		} else {
			// ToastUtils.showShort(this, "网络异常，请稍检查网络");
		}
	}

	/**
	 * @描述：
	 * @param appId
	 */
	private void userSetupRes(Context context, String appId) {
		if (NetUtils.isConnected(context)) {
			request.getRequestData(mHandler, Constant.USER_SETUP_RES,
					"AuthKey", ChargeApplication.getInitInfo().get("AuthKey"),
					"ResId", appId);
		} else {

		}

	}
}
